<template>
  <div class="article-container">
    <el-row>
      <el-col :span="22" :offset="1">
        <!--卡片-->
        <card class="table-container" cardName="公告列表" :scalable="false">
          <!--工具栏-->
          <tool-bar slot="tool" @receiveKeyword="receiveKeyword" @emptyQuery="emptyQuery" class="toolbar">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('notice:insert')">
                <el-button class="toolbar-button" @click="openSaveNotice">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增公告
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('notice:delete')">
                <el-button class="toolbar-button" @click="deleteMultiNotice">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>

            <div slot="customContainer" class="custom-container">
              <el-select v-model="query.type" class="type-select" placeholder="请选择公告类型">
                <el-option
                  v-for="item in noticeTypeArray"
                  :key="item.value"
                  :label="item.type"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </tool-bar>

          <!--卡片里的内容-->
          <el-table
            slot="content"
            ref="noticeTable"
            :data="noticeData"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectNotice"
            @select-all="selectNotice"
            :key="tableKey">
            <el-table-column
              align="center"
              type="selection"
              min-width="45">
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              min-width="400">
            </el-table-column>
            <el-table-column
              align="center"
              prop="link"
              label="链接"
              min-width="80">
              <template slot-scope="scope">
                <el-link
                  v-if="scope.row.link"
                  target="_blank"
                  type="primary" @click="toHref(scope.row)">点击查看链接</el-link>
                <el-link
                  v-else
                  type="info"
                  disabled>
                  该公告没有链接
                </el-link>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="type"
              label="类型"
              min-width="80">
              <template slot-scope="scope">
                <el-tag
                  v-if="scope.row.type == 1"
                  effect="plain"
                  type="primary">
                  {{noticeTypeArray[scope.row.type - 1].type}}
                </el-tag>
                <el-tag
                  v-else
                  effect="plain"
                  type="danger">
                  {{noticeTypeArray[scope.row.type - 1].type}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="50">
              <template slot-scope="scope">
                <el-switch
                  :disabled="!hasPermission('notice:update')"
                  v-model="scope.row.usable"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="updateTime"
              label="更新时间"
              min-width="100">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="100">
              <template slot-scope="scope">
                <span v-if="!hasPermission('notice:delete') && !hasPermission('notice:update')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('notice:update')"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('notice:delete')"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <pagination
      :cp="cpToPagination"
      @getCurrentPage="getCurrentPageFromPagination"
      :total="total"></pagination>
    <show-link-template ref="showLinkTemplate"></show-link-template>
    <save-notice-template
      @reloadTable="loadTableForNotice"
      ref="saveNoticeTemplate"
      :noticeFromParent="noticeForUpdate"></save-notice-template>
  </div>
</template>

<script>
  import Card from 'components/common/card/Card';
  import Pagination from 'components/common/pagination/Pagination';
  import ToolBar from 'components/content/toolbar/ToolBar'
  import ShowLinkTemplate from './subView/ShowLinkTemplate';
  import SaveNoticeTemplate from './subView/SaveNoticeTemplate';

  import {getNoticeByPage, getNoticeCountByType, changeUsable,
    deleteByIds, getNoticeById} from "../../network/viewsRequest/notice";
  import {hasPermission} from "../../common/permission";

  import {MAX_COUNT_OF_USABLE_NOTICE} from "../../common/const";

  export default {
    name: 'NoticeView',
    data() {
      return {
        query: {
          keyword: '', // 搜索关键字
          type: null,
          currentPage: 1,
          pageSize: 10
        },
        noticeTypeArray: [{value: 1, type: '前端页面公告'}, {value: 2, type: '管理后台公告'}],
        noticeData: [],
        multiSelections: [],
        total: 0,
        cpToPagination: 0, // 传递给分页组件当前页的值
        noticeForUpdate: {}, // 传递给SaveNoticeTemplate用于回显的数据
      }
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 清空搜索条件
       */
      emptyQuery() {
        this.query = {
          keyword: '',
          type: null,
          currentPage: 1,
          pageSize: 10
        };
        this.loadTableForNotice();
      },
      /**
       * 点击多选框时触发的方法
       * @param selection 已经选中的集合，
       * @param row 当前选中的行
       */
      selectNotice(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 编辑公告
       * @param index 索引
       * @param row 公告内容
       */
      handleEdit(index, row) {
        getNoticeById(row.id).then(res => {
          if (res.code == 1) {
            this.noticeForUpdate = res.data;
            this.$refs.saveNoticeTemplate.show();
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
            this.noticeForUpdate = {};
          }
        })
      },
      /**
       * 删除公告
       * @param index 索引
       * @param row 公告内容
       */
      handleDelete(index, row) {
        let delIds = [];
        delIds.push(row.id);
        // 调用方法完成删除
        this.deleteLogic(delIds.join());
      },
      /**
       * 批量删除公告
       */
      deleteMultiNotice() {
        // 1.数据校验
        if (this.multiSelections.length === 0) {
          this.$message({
            type: 'error',
            message: '请先选择需要操作的记录!'
          });
          return;
        }
        // 2.进行操作
        let delIds = this.multiSelections.map(item => {
          return item.id;
        })
        this.deleteLogic(delIds.join());
      },
      /**
       * 具体删除操作的逻辑代码
       */
      deleteLogic(ids) {
        this.$confirm('是否要进行删除？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteByIds(ids).then(res => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '删除成功！',
              });
              // 刷新表格数据
              this.loadTableForNotice();
              // 发送信息让公告子组件重新获取数据
              this.$store.commit("getAllBackUsableNotice");
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除操作已经被取消'
          })
        })
      },
      /**
       * 用户点击新增公告按钮时调用的方法
       */
      openSaveNotice() {
        this.$refs.saveNoticeTemplate.show();
      },
      /**
       * 接收子组件toolbar传递过来的搜索关键字keyword
       * @param keyword 搜索关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadTableForNotice();
      },
      /**
       * 用户在点击分页插件时，获取用户点击到的是第几页
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        this.loadTableForNotice();
      },
      /**
       * 获取表格中公告的信息
       */
      loadTableForNotice() {
        getNoticeByPage(this.query).then(res => {
          console.log(res);
          if (res.code == 1) {
            this.noticeData = res.data.items;
            this.total = res.data.total;
          } else {
            this.noticeData = [];
            this.total = 0;
          }

        })
      },
      /**
       * 对于有跳转链接的公告，点击查看对应的链接信息时，调用的方法
       */
      toHref(row) {
        // 1.打开模态框
        this.$refs.showLinkTemplate.show(row);
      },
      /**
       * 点击启用的switch调用的方法
       */
      // TODO 用Promise改写
      changeUsable(row) {
        // 1.启用操作
        if (row.usable == 1) {
          // 1.1.数据校验
          getNoticeCountByType(row.type).then(res => {
            if (res.code == 1) {
              if (res.data >= MAX_COUNT_OF_USABLE_NOTICE) {
                this.$message({
                  type: 'error',
                  message: `可启用的${this.noticeTypeArray[row.type - 1].type}已经达到上限，请先进行禁用操作`
                });
                this.loadTableForNotice();
                return;
              }
              // 1.2.进行操作
              this.changeUsableLogic(row);
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        } else { // 2.禁用操作
          // 2.1.直接进行操作
          this.changeUsableLogic(row);
        }
      },
      /**
       * 操作是否可用的具体逻辑代码
       * @param row
       */
      changeUsableLogic(row) {
        this.cpToPagination = 0;
        changeUsable(row.id, row.usable).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '操作成功！'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.message
            });
          };
          // // 刷新表格，显示第一页数据
          // this.query.currentPage = 1;
          // // 将页面信息传递给分页组件
          // this.cpToPagination = 1;
          // 调用store中的方法给显示公告的组件，让它重新调用方法给自己赋值
          this.$store.commit("getAllBackUsableNotice");
          this.loadTableForNotice();
        });
      },
    },
    mounted() {
      this.loadTableForNotice();
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.noticeData.length; i++) {
          key = key + this.noticeData[i].updateTime;
        }
        return key;
      }
    },
    components: {
      Card,
      Pagination,
      ToolBar,
      ShowLinkTemplate,
      SaveNoticeTemplate
    }
  }
</script>

<style scoped>
  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .el-card {
    margin-top: 30px;
  }
  .editBtn {
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff
  }
  .tag-disabled {
    cursor: not-allowed;
  }
  .button-all-container, .custom-container {
    display: inline-block;
    vertical-align: bottom;
  }
  .el-select {
    width: 150px !important;
    height: 36px !important;
    margin-left: 10px;
  }
  .btn-container {
    margin-right: 5px;
  }
  .type-select {
    margin-right: 5px;
  }

</style>

<style>

  .el-input__inner {
    height: 36px !important;
    vertical-align: middle;

  }
  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 14px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }

  .el-select-dropdown__wrap {
    margin-bottom: 0px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
